package dbx

import (
	"fmt"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	glogger "gorm.io/gorm/logger"
	"zhonghui/console/warehouse/cfgx"

	"zhonghui/console/warehouse/envx"
	"zhonghui/console/warehouse/logx"
)

// 全部mysql实例名，对应配置中心的配置名，硬编码
const (
	DbZhKernel      = "zh_kernel"
	DbZhKernelSlave = "zh_kernel_slave"
)

type MysqlIns struct {
	*gorm.DB
}

// NewMysql 初始化mysql
func NewMysql(name string) *gorm.DB {
	cfg := cfgx.Cfg().GetStringMapString("database.mysql." + name)

	// 链接
	dsn := fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?loc=Local&timeout=5s&charset=utf8mb4&collation=utf8mb4_unicode_ci&interpolateParams=true&parseTime=true",
		cfg["username"], cfg["password"], cfg["host"], cfg["database"],
	)

	// 初始化GORM配置
	dbCfg := &gorm.Config{
		Logger: glogger.Default.LogMode(glogger.Info),
	}
	// 测试环境不使用zap日志
	if !envx.InDev() {
		dbCfg.Logger = setZapLogger(logx.Zap().Desugar())
	}

	// 开始连接，之后会自动ping
	gdb, err := gorm.Open(mysql.Open(dsn), dbCfg)
	if err != nil {
		panic(err)
	}

	// 获取原始驱动
	db, err := gdb.DB()
	if err != nil {
		panic(err)
	}

	// 设置连接池
	db.SetMaxIdleConns(30)
	db.SetMaxOpenConns(100)
	db.SetConnMaxLifetime(time.Minute * 30)

	logx.Zap().Infow("Database init succeed", "host", cfg["host"], "database", cfg["database"])

	return gdb
}
